package com.yzt.message.msgdialog;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import androidx.fragment.app.FragmentActivity;

import com.yzt.zhuju.network.entity.message.GiftInfoBean;
import com.yzt.zhuju.MainMenuContsant;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.arouter.RouterMessage;
import com.yzt.zhuju.event.RxBus;
import com.yzt.zhuju.event.main.MainSwitchEvent;
import com.yzt.zhuju.richtext.EmojiTextView;
import com.yzt.zhuju.utils.ActivityManagerUtils;
import com.yzt.zhuju.utils.PreferencesUtils;
import com.yzt.message.custom.RXGiftMessageContent;
import com.yzt.message.R;
import com.yzt.message.activity.ConversationActivity;
import com.yzt.message.util.MessageInfoUtil;
import com.yzt.message.widget.chatinput.utils.TextSpanUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;

import io.rong.imkit.conversation.extension.component.emoticon.AndroidEmoji;
import io.rong.imkit.conversationlist.model.BaseUiConversation;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import rx.Subscription;

/**
 * desc: 消息悬浮窗口工具类
 **/
public class MsgFloatDialogHelper {

    public static final long SHOW_DIALOG_TIME = 5000;

    private final int SHOW_MODE = 0;//0互顶模式下 新消息 顶掉旧消息 1排队模式 新消息等待旧消息展示完后 顺序显示
    private boolean isCurrentShowMsgListView = false;//当前是否显示的是MainActivity MessageListFragment界面
    // fix 单条消息重复弹出问题，
    // 当MainActivity由于内存紧张 被回收时，MessageListFragment内存泄露 出现多MessageListFragment实例时 重复收到弹窗消息
    private final Set<Integer> msgIdCache = new HashSet<>();

    private static MsgFloatDialogHelper mMsgFloatDialogHelper; //单例实例
    private Subscription mSubscription; //订阅的rxbus 集
    private Queue<BaseUiConversation> msgQueue; //排队模式 下的消息队列
    private Handler mHandler;
    private final List<MsgFloatDialog> msgFloatDialogs = new ArrayList<>();// 互顶模式下的dialog
    //排队模式下，弹出模式 是否是 自启动 ，当为true 时新进入的消息不会调用 execQueue，当屏幕有dialog时 监听此dialog 关闭后 变为true
    // 当execQueue为空时 改值变为false
    private boolean isAutoRun = false;
    private boolean isInit;//是否准备好

    public static MsgFloatDialogHelper getInstance() {
        if (mMsgFloatDialogHelper == null) {
            synchronized (MsgFloatDialogHelper.class) {
                mMsgFloatDialogHelper = new MsgFloatDialogHelper();
            }
        }
        return mMsgFloatDialogHelper;
    }

    private MsgFloatDialogHelper() {

    }

    /**
     * 消息飘屏弹窗
     */
    public void showFloatDialog(Context context, BaseUiConversation uiConversation) {

        // 新消息飘屏权限判断
        if (!PreferencesUtils.getNotifyPopFlutter()) {
            return;
        }

        if (!isInit) {
            return;
        }
        //过滤掉不必要弹出的消息
        if (isFilterThis(uiConversation)) {
            return;
        }
        if (msgIdCache.contains(uiConversation.mCore.getLatestMessageId())) {
            //此消息是否已经弹出过
            return;
        }
        msgIdCache.add(uiConversation.mCore.getLatestMessageId());
        //放入队列
        putInQueue(uiConversation);
        if (SHOW_MODE == 0) {
            execQueue(context);
        } else {
            if (!isAutoRun) {
                isAutoRun = true;
                execQueue(context);
            }
        }
    }

    /**
     * 执行队列
     */
    private void execQueue(Context context) {
        if (msgQueue == null) {
            return;
        }
        BaseUiConversation uiConversation = msgQueue.poll();
        if (uiConversation == null) {
            isAutoRun = false;
            return;
        }
        if (isFilterThis(uiConversation)) {
            isAutoRun = false;
            return;
        }
        try {
            //无权限启动窗口
            showDialogNotPermission(context, uiConversation);
        } catch (Exception e) {
            e.printStackTrace();
            isAutoRun = false;
        }
    }

    /**
     * 将弹出的消息 存入队列
     */
    private void putInQueue(BaseUiConversation uiConversation) {
        if (msgQueue == null) {
            msgQueue = new LinkedList<>();
        }
        msgQueue.offer(uiConversation);
    }

    /**
     * 是否过滤掉此消息的弹出
     */
    private boolean isFilterThis(BaseUiConversation uiConversation) {
        //是否需要弹出
        if (!PreferencesUtils.isMsgFloatDialog()) {
            if (msgQueue != null) {
                msgQueue.clear();
            }
            return true;
        }
        FragmentActivity topActivity = ActivityManagerUtils.getInstance().getTopActivity();
        if (topActivity == null) {
            return true;
        }
//        if (RouterCall.getCallChatActivityClassAllPathName().contains(topActivity.getClass().getSimpleName())) {
//            return true;
//        }
        if (RouterMessage.getMessageListActivityClassAllPathName().contains(topActivity.getClass().getSimpleName())) {
            return true;
        }
        if (topActivity instanceof ConversationActivity) { //聊天界面不弹
            if (msgQueue != null) {
                msgQueue.clear();
            }
            return true;
        }
        if (RouterMain.getMainActivityClassAllPathName().contains(topActivity.getClass().getSimpleName())) { //消息界面不弹
            if (isCurrentShowMsgListView) {
                if (msgQueue != null) {
                    msgQueue.clear();
                }
                return true;
            }
        }

        //部分消息类型不弹
        return MessageInfoUtil.isNeedFilter(uiConversation.mCore.getSenderUserId()) || MessageInfoUtil.isNeedFilterMessageContent(uiConversation.mCore.getLatestMessage());
    }

    /**
     * 不需要权限 直接使用activity context 在当前界面弹出
     */
    private void showDialogNotPermission(Context context, BaseUiConversation uiConversation) {
        FragmentActivity topActivity = ActivityManagerUtils.getInstance().getTopActivity();
        if (SHOW_MODE == 0) {
            //挤掉模式
            //将旧的dialog dismiss
            for (MsgFloatDialog dialog : msgFloatDialogs) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
            MsgFloatDialog msgFloatDialog = createFloatDialog(topActivity, uiConversation, false);
            msgFloatDialog.setOnDismissListener(v -> {
                msgFloatDialogs.remove(msgFloatDialog);
            });
            msgFloatDialog.show();
            msgFloatDialogs.add(msgFloatDialog);
        } else {//排队模式
            //当关闭的时候，检查队列是否有数据，有的话继续弹出
            MsgFloatDialog mMsgFloatDialog = createFloatDialog(topActivity, uiConversation, false);
            mMsgFloatDialog.setOnDismissListener(v -> {
                //过滤出dialog消失动画占用的时间
                if (mHandler != null) {
                    mHandler.postDelayed(() -> execQueue(context), 300);
                }
            });
            mMsgFloatDialog.show();
        }
    }

    /**
     * 创建悬浮窗
     */
    private MsgFloatDialog createFloatDialog(Context context, BaseUiConversation uiConversation, boolean isHavePermission) {
        MsgFloatDialog mMsgFloatDialog = new MsgFloatDialog(context, R.style.TopMsgDialogCustomeStyle);
        if (isHavePermission) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mMsgFloatDialog.getWindow().setType((WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY));
            } else {
                mMsgFloatDialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
            }
        }
        View inflate = LayoutInflater.from(context).inflate(R.layout.dialog_msg_float, null, false);
        MsgFloatView msgFloat = inflate.findViewById(R.id.mfv_msg_float);
        msgFloat.setOnClickListener(v -> mMsgFloatDialog.dismiss());
        EmojiTextView tvContent = msgFloat.getTvContent();
        CharSequence content;
        if (uiConversation.mCore.getMentionedCount() != 0) {
            content = handleMentionedContent(context, uiConversation, tvContent);
        } else {
            content = handleCommonContent(context, uiConversation, tvContent);
        }
        //设置会话标题
        String url = "";
        if (uiConversation.mCore.getPortraitUrl() != null) {
            url = uiConversation.mCore.getPortraitUrl();
        }
        msgFloat.set(url, uiConversation.mCore.getConversationTitle(), content, uiConversation.mCore.getTargetId());
        mMsgFloatDialog.setContentView(inflate);
        return mMsgFloatDialog;
    }

    public static Message getMessage(BaseUiConversation data) {
        List<Message> historyMessages = RongIMClient.getInstance().getHistoryMessages(data.mCore.getConversationType(), data.mCore.getTargetId(), -1, 1);
        for (int i = 0; i < historyMessages.size(); i++) {
            if (data.mCore.getLatestMessageId() == historyMessages.get(i).getMessageId()) {
                return historyMessages.get(i);
            }
        }
        return null;
    }

    public static CharSequence handleMentionedContent(Context context, final BaseUiConversation data, EmojiTextView tvContent) {
        final int empirical_value = 60;//经验值，部分机型上不做调整无法打点。
        final SpannableStringBuilder builder = new SpannableStringBuilder();
        SpannableString string;
        final String preStr = tvContent.getResources().getString(io.rong.imkit.R.string.rc_message_content_mentioned);
        if (tvContent.getWidth() > empirical_value) {
            CharSequence cutStr = TextUtils.ellipsize(preStr + " " + data.mConversationContent, tvContent.getPaint(), tvContent.getWidth() - empirical_value, TextUtils.TruncateAt.END);
            string = new SpannableString(cutStr);
            int colorSpanLength = preStr.length();
            if (colorSpanLength > cutStr.length()) {
                colorSpanLength = cutStr.length();
            }
            if (TextSpanUtils.isCanSetSpan(0, colorSpanLength)) {
                string.setSpan(new ForegroundColorSpan(Color.parseColor("#cc3333")), 0, colorSpanLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            builder.append(string);
            AndroidEmoji.ensure(builder);
            return builder;
        } else {
            if (tvContent.getWidth() > empirical_value) {
                CharSequence cutStr = TextUtils.ellipsize(preStr + " " + data.mConversationContent, tvContent.getPaint(), tvContent.getWidth() - 40, TextUtils.TruncateAt.END);
                SpannableString str = new SpannableString(cutStr);
                int colorSpanLength = preStr.length();
                if (colorSpanLength > cutStr.length()) {
                    colorSpanLength = cutStr.length();
                }
                if (TextSpanUtils.isCanSetSpan(0, colorSpanLength)) {
                    str.setSpan(new ForegroundColorSpan(Color.parseColor("#cc3333")), 0, colorSpanLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                builder.append(str);
            } else {
                String oriStr = preStr + " " + data.mConversationContent;
                SpannableString str = new SpannableString(oriStr);
                if (TextSpanUtils.isCanSetSpan(0, preStr.length())) {
                    str.setSpan(new ForegroundColorSpan(Color.parseColor("#cc3333")), 0, preStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                builder.append(str);
            }
            AndroidEmoji.ensure(builder);
            return builder;
        }
    }

    public static CharSequence handleCommonContent(Context context, final BaseUiConversation data, EmojiTextView tvContent) {
        final CharSequence cutStr;
        //清除聊天记录后，会话内容为空
        //解决表情显示不全

        //加入打招呼礼物的逻辑判断
        if (data.mCore.getLatestMessage() instanceof RXGiftMessageContent) {
            RXGiftMessageContent rxGiftMessageContent = (RXGiftMessageContent) data.mCore.getLatestMessage();
            GiftInfoBean extra = rxGiftMessageContent.getMessageExtra();
//            if (extra != null && extra.size() > 0) {
//                if (extra.containsKey("isGreetGift")) {
//                    SpannableStringBuilder builder = new SpannableStringBuilder();
//                    String preStr = "[对方发来打招呼礼物]";
//                    SpannableString string = new SpannableString(preStr);
//                    Message lastMessage = getMessage(data);
//                    if (lastMessage != null) {
//                        LogDataUtils.d("session_list_message", lastMessage.toString());
//                        UiMessage uiMessage = new UiMessage(lastMessage);
//                        if (uiMessage.getMessageDirection() == Message.MessageDirection.SEND) {
//                            string = new SpannableString("[打招呼礼物]");
//                        } else {
//                            String isRead = uiMessage.getExtra();
//                            if (!TextUtils.equals(isRead, "1")) {
//                                if (TextSpanUtils.isCanSetSpan(0, preStr.length())) {
//                                    string.setSpan(new ForegroundColorSpan(Color.parseColor("#cb120f")), 0, preStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                                }
//                            }
//                        }
//                    }
//                    builder.append(string);
//                    return builder;
//                }
//            }
        }
        final int empirical_value = 60;//经验值，部分机型上不做调整无法打点。
        if (tvContent.getWidth() > empirical_value && data.mConversationContent != null) {
            cutStr = TextUtils.ellipsize(data.mConversationContent, tvContent.getPaint(),
                    tvContent.getWidth() - empirical_value, TextUtils.TruncateAt.END);
            //            }
            return cutStr;
        } else {
            cutStr = data.mConversationContent;
            if (tvContent.getWidth() > empirical_value && cutStr != null) {
                CharSequence str = TextUtils.ellipsize(cutStr, tvContent.getPaint(),
                        tvContent.getWidth() - empirical_value, TextUtils.TruncateAt.END);
                return str;
            } else {
                return cutStr;
            }
        }
    }

    /**
     * 初始化 消息弹窗模块
     */
    public void init() {
        if (isInit) { //防止重复初始化
            return;
        }
        isInit = true;
        mSubscription = RxBus.getDefault().observerRxBus(MainSwitchEvent.class, mainSwitchEvent -> {
            isCurrentShowMsgListView = mainSwitchEvent.getIndex() == MainMenuContsant.getIndex(MainMenuContsant.MAIN_MENU_MSG);
        });
        mHandler = new Handler();
//        BizLayer.getInstance().getMineModule().getNoticeInfo(new AresSubscriber<NoticePrivateInfo>() {
//            @Override
//            protected void onSuccess(NoticePrivateInfo noticePrivateInfo) {
//                PreferencesUtils.setMsgFloatDialog(noticePrivateInfo.getNotice8() == 1);
//            }
//        });
    }

    /**
     * 是否消息弹窗模块
     */
    public void release() {
        isInit = false;
        if (mSubscription != null) {
            if (!mSubscription.isUnsubscribed()) {
                mSubscription.unsubscribe();
            }
            mSubscription = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }
}
